<?php

/**
 * Action 基础抽象类
 *
 * @author littlexiang
 * @version $Id: Controller.php 685 2009-08-03 06:28:25Z songxiang $
 * 
 * @property $_view
 */

abstract class Controller {
    
    public function indexAction () {
        throw new Controller_Exception('IndexAction not defined in Controller ');
    }
    
    /**
     * Inner forward
     *
     * @param string $uri like 'index/index'
     * @throws Exception when uri format is incorrect
     * @throws Exception when forward is done to stop the flow
     */
    public function forward ($uri) {
        if (preg_match('~^[0-9a-z]+/?[0-9a-z]*$~', $uri)) {
            list ($controller, $action) = explode('/', $uri);
            View::$data = array();
            Dispatcher::forward($controller, $action);
            // 为了让调用了forward之后，不能再执行其他的代码，抛出异常。该异常会被Journey::start()接收并忽略
            throw new Dispatcher_StopException('Forward end and stop dispatching');
        } else {
            throw new Dispatcher_Exception('Uri format not correct');
        }
    }
    
    /**
     * 302 jump, force quit after redirect
     *
     * @param string $uri like 'index/index'
     * @param array $param
     * @throws Exception when uri format is incorrect
     * @throws Exception when forward is done to stop the flow
     */
    public function redirect ($uri, array $params = array()) {
        if (preg_match('~^[0-9a-z]+/?[0-9a-z]*$~', $uri)) {
            $uri = Uri::make($uri, $params);
            
            session_commit();
            header('Location: ' . $uri);
            throw new Dispatcher_StopException('Redirect end and stop dispatching');
        } else {
            throw new Dispatcher_Exception('Uri format not correct');
        }
    }
    
    public function makeUri ($string, array $param = array()) {
        return Uri::make($string, $param);
    }
    
    public function assign ($name, $value) {
        $this->$name = $value;
    }
    
    public function __set ($name, $value) {
        if (! isset(View::$data[$name])) {
            View::$data[$name] = $value;
        } else {
            throw new Exception('Tring to assign another value for "'. $name . '"');
        }
    
    }

}
?>